﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Host
{

    public class AssemblyPathEx
    {
        static void AddEnvironmentPaths(IEnumerable<string> paths)
        {
            var path = new[] { Environment.GetEnvironmentVariable("PATH") ?? string.Empty };
            string newPath = string.Join(Path.PathSeparator.ToString(), path.Concat(paths));
            Environment.SetEnvironmentVariable("PATH", newPath);
        }

        private static AssemblyPathEx ex = new AssemblyPathEx();

        private AssemblyPathEx()
        {
            AddEnvironmentPaths(new string[] { Path.Combine(Directory.GetCurrentDirectory(), "Hosts") });
        }
    }

    public static class AssemblyEx
    {
        /// <summary>
        /// 搜索全局变量中的Dll
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static Assembly SearchAssembly(string name)
        {
            string[] DllNames = new string[] { ".dll", ".exe" };

            Assembly item_calss = null;

            foreach (var path in (Environment.GetEnvironmentVariable("PATH") ?? string.Empty).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                foreach (var dll_name in DllNames)
                {
                    var file_path = Path.Combine(path, name + dll_name);
                    if (File.Exists(file_path))
                    {
                        //byte[] buffer = System.IO.File.ReadAllBytes(file_path);
                        //item_calss = Assembly.Load(buffer);
                        item_calss = Assembly.LoadFile(file_path);
                        break;
                    }
                }
            }

            return item_calss;
        }
    }
}
